using Digitalmes.Common.Result;

namespace Digitalmes.ApiService.Middleware;

/// <summary>
/// 异常处理中间件
/// </summary>
public sealed class ExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IHostEnvironment _hostEnvironment;
    private readonly ILogger _logger;

    public ExceptionMiddleware(RequestDelegate next, IHostEnvironment hostEnvironment, ILogger<ExceptionMiddleware> logger)
    {
        _next = next;
        _hostEnvironment = hostEnvironment;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await ExceptionHandlerAsync(context, ex);
        }
    }

    private async Task ExceptionHandlerAsync(HttpContext context, Exception ex)
    {
        context.Response.ContentType = "application/json";
        var message = "服务端发生异常，请稍后重试~";
        if (_hostEnvironment.IsDevelopment())
        {
            message = ex.Message;
            _logger.LogError(ex, "服务端异常");
        }

        var result = JsonSerializer.Serialize(new ApiResult<string>()
        {
            Code = (int)HttpStatusCode.InternalServerError,
            Message = message
        });
        await context.Response.WriteAsync(result.ToLower());
    }
}
